package com.how2java.tmall.service;

import com.how2java.tmall.dao.ProductImageDao;
import com.how2java.tmall.pojo.OrderItem;
import com.how2java.tmall.pojo.Product;
import com.how2java.tmall.pojo.ProductImage;
import com.how2java.tmall.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = "productImages")
public class ProductImageService {

    public static final String type_single="single";
    public static final String type_detail="detail";

    @Autowired
    private ProductImageDao productImageDao;

    @CacheEvict(allEntries = true)
    public void add(ProductImage bean){
        productImageDao.save(bean);
    }

    @CacheEvict(allEntries = true)
    public void delete(int id){
        productImageDao.delete(id);
    }

    @CacheEvict(allEntries = true)
    public void update(ProductImage bean){
        productImageDao.save(bean);
    }

    @Cacheable(key="'productImages-one-'+#p0")
    public ProductImage get(int id){
        return productImageDao.findOne(id);
    }

    @Cacheable(key="'productImages-single-'+#p0.id")
    public List<ProductImage> listSingleProductImages(Product product){
        return productImageDao.findByProductAndTypeOrderByIdDesc(product,type_single);
    }

    @Cacheable(key="'productImages-detail-'+#p0.id")
    public List<ProductImage> listDetailProductImages(Product product){
        return productImageDao.findByProductAndTypeOrderByIdDesc(product,type_detail);
    }


    /**
     * 设置产品列表的缩略图
     * @param productList
     */
    public void setFirstProductImages(List<Product> productList){
        for(Product product : productList){
            setFirstProductImage(product);
        }
    }


    public void setFirstProductImage(Product product){
        ProductImageService productImageService = SpringContextUtil.getBean(ProductImageService.class);
        List<ProductImage> singleImages = productImageService.listSingleProductImages(product);
        if(!singleImages.isEmpty()){
            product.setFirstProductImage(singleImages.get(0));
        }else{
            product.setFirstProductImage(new ProductImage());
        }
    }


    public void setFirstProductImagesOnorderItems(List<OrderItem> ois){
        for(OrderItem oi : ois){
            setFirstProductImage(oi.getProduct());
        }
    }




}
